package com.atguigu.cmsservice.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.cmsservice.entity.CrmBanner;
import com.atguigu.cmsservice.mapper.CrmBannerMapper;
import com.atguigu.cmsservice.service.CrmBannerService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 首页banner表 服务实现类
 * </p>
 *
 * @author huangqicai
 * @since 2022-10-25
 */
@Service
public class CrmBannerServiceImpl extends ServiceImpl<CrmBannerMapper, CrmBanner> implements CrmBannerService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    /*下面这个注解是用于将返回数据加入到redis里面*/
    public List<CrmBanner> getAllBanner() {
        String bannerKey="banner:";
        /*1.先去redis里面查询数据*/
        String redisValue=new String();
        redisValue = stringRedisTemplate.opsForValue().get(bannerKey);
        List<CrmBanner> crmBanners=new ArrayList<>();
        /*2.判断是否查询到了数据*/
        if(StringUtils.isEmpty(redisValue)){
            /*3.redis里面没有数据，就去数据库里面查询*/
            QueryWrapper<CrmBanner> wrapper = new QueryWrapper<>();
            wrapper.orderByDesc("id");
            wrapper.last("limit 2");
            crmBanners = baseMapper.selectList(wrapper);
        }else {
            List<CrmBanner> res = JSONObject.parseArray(redisValue, CrmBanner.class);
            return res;
        }
        if(!StringUtils.isEmpty(crmBanners)){
            /*4.数据库里面的数据不为空，保存到redis里面*/
            String res = JSONObject.toJSONString(crmBanners);
            stringRedisTemplate.opsForValue().set(bannerKey, res);
            return crmBanners;
        }else {
            return null;
        }
    }

}
